# import uuid
# import os
# import time
# import asyncio
# from pathlib import Path
# from fastapi import FastAPI, UploadFile, File, HTTPException, Form
# from fastapi.responses import JSONResponse
# from typing import List
# from PIL import Image
# import fitz  # PyMuPDF
#
# # 导入 RapidOCR
# try:
#     from rapidocr_onnxruntime import RapidOCR
# except ImportError:
#     raise ImportError(
#         "Failed to import rapidocr_onnxruntime. "
#         "Please install: pip install rapidocr-onnxruntime"
#     )
#
# # 初始化 FastAPI 应用
# app = FastAPI(
#     title="OCR识别API (RapidOCR)",
#     description="支持文件上传进行OCR识别，使用RapidOCR，支持真正的并发处理"
# )
#
#
# def init_rapidocr():
#     """初始化 RapidOCR（线程安全，可多实例并发）"""
#     try:
#         ocr = RapidOCR()
#         print("✓ RapidOCR 初始化成功")
#         return ocr
#     except Exception as e:
#         print(f"✗ RapidOCR 初始化失败: {e}")
#         raise
#
#
# def perform_ocr_with_rapidocr(image_path):
#     """
#     使用 RapidOCR 执行 OCR 识别
#
#     Args:
#         image_path: 图片路径
#
#     Returns:
#         dict: 包含识别文本和详细信息的字典
#     """
#     try:
#         ocr = init_rapidocr()
#
#         # RapidOCR 识别
#         # 返回: (result, elapse_time)
#         # result: [[[x1,y1],[x2,y2],[x3,y3],[x4,y4]], text, score]
#         result, elapse = ocr(str(image_path))
#
#         if result is None:
#             return {
#                 'texts': [],
#                 'full_text': '',
#                 'detailed_results': [],
#                 'text_count': 0
#             }
#
#         # 提取文本和详细信息
#         texts = []
#         detailed_results = []
#
#         for item in result:
#             bbox, text, score = item
#             texts.append(text)
#
#             # 保存详细信息
#             detailed_results.append({
#                 'text': text,
#                 'confidence': float(score),
#                 'bbox': {
#                     'points': bbox  # 四个点坐标
#                 }
#             })
#
#         # 拼接所有文本
#         full_text = '\n'.join(texts)
#
#         return {
#             'texts': texts,
#             'full_text': full_text,
#             'detailed_results': detailed_results,
#             'text_count': len(texts),
#             'elapse_time': elapse
#         }
#
#     except Exception as e:
#         raise Exception(f"RapidOCR 识别失败: {str(e)}")
#
#
# def process_single_file_ocr(file_content: bytes, filename: str, file_id: str = None):
#     """
#     处理单个文件的OCR识别（使用 RapidOCR）
#
#     Args:
#         file_content: 文件内容（字节）
#         filename: 文件名
#         file_id: 文件ID
#
#     Returns:
#         dict: OCR识别结果
#     """
#     base_dir = Path(__file__).parent.parent
#     tmp_dir = base_dir / "tmp"
#     tmp_dir.mkdir(exist_ok=True)
#
#     if file_id is None:
#         file_id = str(uuid.uuid4())
#
#     file_ext = Path(filename).suffix.lower() if filename else ''
#     input_file_path = tmp_dir / f"{file_id}{file_ext}"
#
#     try:
#         # 保存文件
#         with open(input_file_path, "wb") as buffer:
#             buffer.write(file_content)
#
#         # 执行 OCR
#         ocr_start_time = time.time()
#         ocr_result = perform_ocr_with_rapidocr(input_file_path)
#         ocr_time = time.time() - ocr_start_time
#
#         print("=" * 80)
#         print(f"RapidOCR 识别完成:")
#         print(f"  识别耗时: {ocr_time:.2f} 秒")
#         print(f"  识别文本数: {ocr_result['text_count']}")
#         print("=" * 80)
#
#         # 构建返回结果
#         response_data = {
#             "status": "success",
#             "file_id": file_id,
#             "original_filename": filename,
#             "ocr_engine": "RapidOCR",
#             "results": ocr_result['detailed_results'],
#             "all_texts": ocr_result['texts'],
#             "full_text": ocr_result['full_text'],
#             "text_count": ocr_result['text_count'],
#             "ocr_time": ocr_time
#         }
#
#         return response_data
#
#     finally:
#         # 删除临时文件
#         try:
#             if input_file_path.exists():
#                 input_file_path.unlink()
#         except Exception as e:
#             print(f"删除临时文件失败: {e}")
#
#
# async def process_single_file_async(content: bytes, filename: str, idx: int, total: int):
#     """
#     异步处理单个文件的OCR识别（RapidOCR 支持真正的并发）
#
#     Args:
#         content: 文件内容（字节）
#         filename: 文件名
#         idx: 文件序号
#         total: 文件总数
#
#     Returns:
#         str: OCR识别的文本结果或错误信息
#     """
#     file_start_time = time.time()
#     print(f"\n[并发任务 {idx}/{total}] 开始处理: {filename}")
#
#     try:
#         # RapidOCR 支持真正的并发，无需信号量保护
#         # 直接使用 asyncio.to_thread
#         result = await asyncio.to_thread(
#             process_single_file_ocr,
#             content,
#             filename,
#             None  # file_id
#         )
#
#         file_time = time.time() - file_start_time
#         print(f"[并发任务 {idx}/{total}] 文件 {filename} 处理完成，耗时: {file_time:.2f} 秒")
#
#         return result["full_text"]
#
#     except Exception as e:
#         error_msg = str(e)
#         file_time = time.time() - file_start_time
#         print(f"[并发任务 {idx}/{total}] 文件 {filename} 处理失败 (耗时 {file_time:.2f} 秒): {error_msg}")
#         return f"[处理失败: {filename}]"
#
#
# @app.get("/")
# async def root():
#     """根路径，返回 API 信息"""
#     return {
#         "message": "OCR识别API (RapidOCR)",
#         "status": "running",
#         "ocr_engine": "RapidOCR",
#         "concurrent_support": True,
#         "features": ["轻量级", "多线程", "高准确率"]
#     }
#
#
# @app.post("/ocr")
# async def upload_and_ocr(file: UploadFile = File(...)):
#     """
#     上传文件并进行OCR识别
#
#     Args:
#         file: 上传的文件
#
#     Returns:
#         JSONResponse: OCR识别结果
#     """
#     try:
#         content = await file.read()
#         result = process_single_file_ocr(content, file.filename)
#         return JSONResponse(result["full_text"])
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))
#
#
# @app.post("/ocr_batch")
# async def upload_and_ocr_batch(files: List[UploadFile] = File(...)):
#     """
#     批量上传文件并进行OCR识别 - 支持真正的并发处理
#
#     本接口采用真正的并发处理模式：
#     - RapidOCR 天然支持多线程并发
#     - 无需信号量限制，所有任务同时执行
#     - 处理速度是顺序处理的 N 倍（N = 并发数）
#
#     Args:
#         files: 上传的文件列表
#
#     Returns:
#         JSONResponse: 所有文件OCR识别结果的列表
#     """
#     batch_start_time = time.time()
#
#     print("=" * 80)
#     print(f"批量OCR处理开始，共 {len(files)} 个文件")
#     print(f"处理模式: 真正的并发（RapidOCR 线程安全）")
#     print("=" * 80)
#
#     # 准备所有任务
#     tasks = []
#     for idx, file in enumerate(files, 1):
#         content = await file.read()
#         task = process_single_file_async(content, file.filename, idx, len(files))
#         tasks.append(task)
#
#     # 真正的并发执行（无需延迟，无需信号量）
#     results = await asyncio.gather(*tasks)
#
#     batch_time = time.time() - batch_start_time
#
#     print("=" * 80)
#     print(f"批量OCR处理完成:")
#     print(f"  成功: {sum(1 for r in results if not r.startswith('[处理失败'))}")
#     print(f"  失败: {sum(1 for r in results if r.startswith('[处理失败'))}")
#     print(f"  总耗时: {batch_time:.2f} 秒")
#     print(f"  平均每个文件: {batch_time/len(files):.2f} 秒")
#     print("=" * 80)
#
#     return JSONResponse(results)
#
#
# if __name__ == "__main__":
#     import uvicorn
#
#     print("=" * 80)
#     print("启动 RapidOCR API 服务")
#     print("特性:")
#     print("  ✓ 真正的多线程并发")
#     print("  ✓ 轻量级（~20MB）")
#     print("  ✓ 高准确率（90-95%）")
#     print("  ✓ NPU/CPU 支持")
#     print("=" * 80)
#
#     uvicorn.run(app, host="0.0.0.0", port=8871)
